package com.enjoybyte.pangu.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.jwt.JWT;
import com.enjoybyte.pangu.entity.LoginUser;
import com.enjoybyte.pangu.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api")
public class SysController {

    private static final byte[] key = "pangu".getBytes();

    @GetMapping("/getCaptcha")
    public Result getCaptcha(HttpServletRequest request) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(120, 40);
        log.info("验证码：{}",lineCaptcha.getCode());
        //todo 模拟验证码存入缓存，此处用session替代
        request.getSession().setMaxInactiveInterval(120);
        request.getSession().setAttribute("captcha", lineCaptcha.getCode());
        return Result.ok(lineCaptcha.getImageBase64Data());
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginUser loginUser, HttpServletRequest request) {
        //session中获取验证码
        String captchaPost = (String) request.getSession().getAttribute("captcha");
        if(loginUser.getPassword().equals("123456") && loginUser.getCaptcha().equalsIgnoreCase(captchaPost)) {
            String token = JWT.create()
                    .setPayload("sub", loginUser.getUsername())
                    .setKey(key)
                    .sign();
            request.getSession().removeAttribute("captcha");
            log.info("token:{}",token);
            return Result.ok(token);
        }else{
            return Result.fail(500,"登录失败！");
        }
    }

    
}
